<?php
/**
 * file video.php
 * Created on 2015-3-25 下午4:51:29 
 * Create by xiweijie
 */
namespace haibao\cms\data;

use \haibao\frame\data\query\Condition;
use \haibao\cms\model\filter\User as UserFilter;
use \haibao\cms\model\filter\Video as VideoFilter;
use \haibao\cms\model\filter\VideoCategory as VideoCategoryFilter;
use \haibao\cms\model\filter\VideoProperty as VideoPropertyFilter;
use \haibao\cms\model\filter\VideoRelTag as VideoRelTagFilter;

class Video extends BaseMysql{
    
    public function __construct(){
        parent::__construct('\haibao\cms\model\data\Video');
    }
    
    public function addVideoWap($model,$channelTagId){
        $sql = 'select Id from WapInfo where InfoId = %s and InfoType=%s limit 1';
        $result = $this->query($sql,array($model->Id,\haibao\cms\model\data\WapInfo::INFO_TYPE_VIDEO))->fetch_assoc();
        if($result){
            if(empty($model->VideorelTagModel)){
                $sql = 'update WapInfo set Title=%s,TagId=%s,PublishTime=%s,Published=0 where InfoId=%s and InfoType=%s';
                $this->query($sql,array($model->Title,$channelTagId,$model->PublishDate,$model->Id,\haibao\cms\model\data\WapInfo::INFO_TYPE_VIDEO));
            }else{
                $sql = 'update WapInfo set Title=%s,TagId=%s,PublishTime=%s,Published=%s where InfoId=%s and InfoType=%s';
                $this->query($sql,array($model->Title,$channelTagId,$model->PublishDate,$model->Published,$model->Id,\haibao\cms\model\data\WapInfo::INFO_TYPE_VIDEO));
            }
        }else{
            $wapInfoModel = new \haibao\cms\model\data\WapInfo();
            $wapInfoModel->InfoId = $model->Id;
            $wapInfoModel->Title = $model->Title;
            $wapInfoModel->CreateBy = $model->LastModifyUser;
            $wapInfoModel->CreateTime = $model->LastModifyTime;
            $wapInfoModel->Author = $model->UserName;
            $wapInfoModel->Published = $model->Published;
            $wapInfoModel->PublishTime = $model->PublishDate;
            $wapInfoModel->InfoType = $wapInfoModel::INFO_TYPE_VIDEO;
            $wapInfoModel->IndexTop = $wapInfoModel::INDEX_TOP_NO;
            $wapInfoModel->ChannelTop = $wapInfoModel::CHANNEL_TOP_NO;
            $wapInfoModel->PublishId = $model->Id;
            $wapInfoModel->Level = 4;//$model->Level;
            $wapInfoModel->TagId = $channelTagId;
            $this->add($wapInfoModel);
        }
    }
    
    public function updateVideoStatus($infoId){
        $sql = 'update WapInfo set Status=%s where InfoId=%s and InfoType=%s';
        $this->query($sql,array(1,$infoId,\haibao\cms\model\data\WapInfo::INFO_TYPE_VIDEO));
    }
    
    public function getNewFiveVideos(){
    	$data = array();
    	$sql = 'select t1.Id,t1.Title,t3.Filename from Video t1 ';
    	$sql .= ' inner join ImageLibrary t3 on t1.PicId=t3.Id';
    	$sql .= ' where t1.Published = '.\haibao\cms\model\data\Video::PUBLISHED_OK.' and not exists ';
    	$sql .= ' (select t2.Id from Video t2 where t2.PublishDate > t1.PublishDate and t1.CategoryId = t2.CategoryId)';
    	$sql .= ' order by t1.PublishDate desc limit 5';
    	$result = $this->query($sql);
    	while ($row = $result->fetch_assoc()){
    		array_push($data,$row);
    	}
    	
    	return $data;
    }
    
    public function searchIdsByKeywordFilter($filter){
    	$ids = array();
    	$sengine = new \haibao\cms\sengine\SphinxDb();
    	$result = $sengine->search($filter);
    	if (!empty($result['matches'])){
    		$filter->getPager()->setResultCount($result['total']);
    		foreach ($result['matches'] as $match){
    			array_push($ids,$match['attrs']['recordid']);
    		}
    	}
    	
    	return $ids;
    }
    
    public function addVideo($model,$tagIdList = array()){
        $this->beginTranscation();
        
        try{
            $this->add($model);
            $this->addVideoProperty($model);
            $this->addVideoTelTag($model);
            
            //操作聚合记录
            if($model->Published == 1){
            	$data = new \haibao\cms\data\PolymerInfo();
            	$data->processPolymerInfoVideo($model,$tagIdList,true);
            }
        
        } catch(\Exception $e){
        
            $this->rollback();
            throw $e;
        
        }
        $this->endTranscation();
        
        return $model;
    }
    
    public function addVideoProperty($model){
        if(!empty($model->VideoPropertyModel)){
            $model->VideoPropertyModel->VideoId = $model->Id;
            $this->add($model->VideoPropertyModel);
        }
    }

    public function getVideoById($id){
    $videoFilter = new VideoFilter();
            $videoPropertyFilter = new VideoPropertyFilter();
            $videoCategoryFilter = new VideoCategoryFilter();
            $videoRelTagFilter = new VideoRelTagFilter();
            $userFilter = new UserFilter();
        
            $videoFilter->select(array(
                VideoFilter::CONDITION_FIELD_NAME_ID,
                VideoFilter::CONDITION_FIELD_NAME_TITLE,
                VideoFilter::CONDITION_FIELD_NAME_VIDEOURL,
                VideoFilter::CONDITION_FIELD_NAME_URLH5,
                VideoFilter::CONDITION_FIELD_NAME_LASTMODIFYUSER,
                VideoFilter::CONDITION_FIELD_NAME_LASTMODIFYTIME,
                VideoFilter::CONDITION_FIELD_NAME_PUBLISHDATE,
                VideoFilter::CONDITION_FIELD_NAME_CATEGORYID,
                VideoFilter::CONDITION_FIELD_NAME_SOURCE,
                VideoFilter::CONDITION_FIELD_NAME_DETAILURL,
                VideoFilter::CONDOTION_FIELD_NAME_DESCRIPTION,
                VideoFilter::CONDITION_FIELD_NAME_PICID,
                VideoFilter::CONDITION_FIELD_NAME_SURFACE_PICID,
            	VideoFilter::CONDITION_FIELD_NAME_VOLNUM,
            	VideoFilter::CONDITION_FIELD_NAME_PROPICURL,
            	VideoFilter::CONDITION_FIELD_NAME_SQUAREPICURL,
                VideoFilter::CONDITION_FIELD_NAME_PUBLISHED,
            	VideoFilter::CONDITION_FIELD_NAME_FEATUREID,
            	VideoFilter::CONDITION_FIELD_NAME_FOCUSPIC,
            	VideoFilter::CONDITION_FIELD_NAME_FOCUSVIDEO,
            	VideoFilter::CONDITION_FIELD_NAME_FOCUSPIC_STATE
            ));
            $videoCategoryFilter->select(array(
                VideoCategoryFilter::CONDITION_FIELD_NAME_CATEGORYNAME,
                VideoCategoryFilter::CONDITION_FIELD_NAME_STATUS,
                VideoCategoryFilter::CONDITION_FIELD_NAME_ID,
            ));
            $videoPropertyFilter->select(array(
                VideoPropertyFilter::CONDITION_FIELD_NAME_COMMENTNUM,
                VideoPropertyFilter::CONDITION_FIELD_NAME_ID,
                VideoPropertyFilter::CONDITION_FIELD_NAME_PLAYNUM,
                VideoPropertyFilter::CONDITION_FIELD_NAME_PLAYNUMSHOW,
                VideoPropertyFilter::CONDITION_FIELD_NAME_VIDEOID
            ));
            $videoRelTagFilter->select(array(
                VideoRelTagFilter::CONDITION_FIELD_NAME_ID,
                VideoRelTagFilter::CONDITION_FIELD_NAME_ISPARIMARY,
                VideoRelTagFilter::CONDITION_FIELD_NAME_VIDEOID,
                VideoRelTagFilter::CONDITION_FIELD_NAME_TAGID
            ));
            $userFilter->select(array(
                UserFilter::CONDITION_FIELD_NAME_USER_NAME,
            ));
            $videoFilter->leftJoin($videoCategoryFilter,null,VideoFilter::CONDITION_FIELD_NAME_CATEGORYID,VideoCategoryFilter::CONDITION_FIELD_NAME_ID,VideoFilter::CONDITION_FIELD_NAME_CATEGORY);
            $videoFilter->leftJoin($videoPropertyFilter,null,VideoFilter::CONDITION_FIELD_NAME_ID,VideoPropertyFilter::CONDITION_FIELD_NAME_VIDEOID,VideoFilter::CONDITION_FIELD_NAME_PROPERTY);
            $videoFilter->leftJoin($videoRelTagFilter,null,VideoFilter::CONDITION_FIELD_NAME_ID,VideoRelTagFilter::CONDITION_FIELD_NAME_VIDEOID,VideoFilter::CONDITION_FIELD_NAME_TAGS);
            $videoFilter->leftJoin($userFilter,null,VideoFilter::CONDITION_FIELD_NAME_LASTMODIFYUSER,UserFilter::CONDITION_FIELD_NAME_ID,VideoFilter::CONDITION_FIELD_NAME_USERNAME);
            $videoFilter->where(VideoFilter::CONDITION_FIELD_NAME_ID, Condition::CONDITION_EQUAL,$id);
            $video = parent::getOne($videoFilter);
            return $video;
    }
    
    public function updateVideoById($model,$tagIdList = array()){
        $this->beginTranscation();
        
        try{
            parent::updateById($model->Id, array(
                VideoFilter::CONDITION_FIELD_NAME_CATEGORYID=>$model->CategoryId,
                VideoFilter::CONDITION_FIELD_NAME_DETAILURL=>$model->DetailUrl,
                VideoFilter::CONDITION_FIELD_NAME_PICID=>$model->PicId,
                VideoFilter::CONDITION_FIELD_NAME_SURFACE_PICID=>$model->SurfacePicId,
            	VideoFilter::CONDITION_FIELD_NAME_PROPICURL=>$model->ProPicUrl,
            	VideoFilter::CONDITION_FIELD_NAME_SQUAREPICURL=>$model->SquarePicUrl,
                VideoFilter::CONDITION_FIELD_NAME_PUBLISHDATE=>$model->PublishDate,
                VideoFilter::CONDITION_FIELD_NAME_SOURCE=>$model->Source,
                VideoFilter::CONDITION_FIELD_NAME_TITLE=>$model->Title,
                VideoFilter::CONDITION_FIELD_NAME_URLH5=>$model->VideoUrlForH5,
                VideoFilter::CONDITION_FIELD_NAME_VIDEOURL=>$model->VideoUrl,
                VideoFilter::CONDOTION_FIELD_NAME_DESCRIPTION=>$model->Description,
                VideoFilter::CONDITION_FIELD_NAME_LASTMODIFYTIME=>$model->LastModifyTime,
                VideoFilter::CONDITION_FIELD_NAME_LASTMODIFYUSER=>$model->LastModifyUser,
                VideoFilter::CONDITION_FIELD_NAME_PUBLISHED=>$model->Published,
            	VideoFilter::CONDITION_FIELD_NAME_FEATUREID=>$model->FeatureId,
            	VideoFilter::CONDITION_FIELD_NAME_VOLNUM=>$model->VolNum,
            	VideoFilter::CONDITION_FIELD_NAME_FOCUSVIDEO=>$model->FocusVideo,
            	VideoFilter::CONDITION_FIELD_NAME_FOCUSPIC_STATE=>$model->FocusPicState
            ));
            
            $tagSql ="delete from VideoRelTag where VideoId=%s";
            $this->query($tagSql,array($model->Id));
            $this->addVideoTelTag($model);
            
            
            
            //操作聚合记录
            if($model->Published == 1){
            	$data = new \haibao\cms\data\PolymerInfo();
            	$data->processPolymerInfoVideo($model,$tagIdList);
            } else {
            	$data = new \haibao\cms\data\PolymerInfo();
            	$data->updatePolymarInfo($model->Id,\haibao\cms\model\data\PolymerInfo::OBJECT_TYPE_VIDEO,array('Status'=>\haibao\cms\model\data\PolymerInfo::STATUS_DEL));
            }
            	
        }catch (\Exception $e) {
            $this->rollback();
            throw $e;
        }
        $this->endTranscation();
    }
    
    public function addVideoTelTag($model){
        if(!empty($model->VideorelTagModel)){
          $arrTagModel = $model->VideorelTagModel;
          $tagIds = array();
          foreach ($arrTagModel as $tagModel){
              $tagModel->VideoId = $model->Id;  
              $tagIds[] = $tagModel->TagId;
          }
          $this->addAll($arrTagModel);
          
          
          //TT addtime 2015.11.26判断标签是否包含品牌、明星、设计师，如果有，修改品牌、明星或设计师表的updatetime
          if($tagIds){
          	//修改品牌库某品牌记录的修改日期
          	$sql = "update Brand set UpdateTime = '".date('Y-m-d H:i:s')."' where TagId in (".implode(',',$tagIds).")";
          	$this->query ($sql);
          	
          	//修改明星库某明星记录的修改日期
          	$sql = "update Celebrity set UpdateTime = '".date('Y-m-d H:i:s')."' where TagId in (".implode(',',$tagIds).")";
          	$this->query ($sql);
          	
          	//TODO 修改设计师库某设计师记录的修改日期
          	$sql = "update Designer set UpdateTime = '".date('Y-m-d H:i:s')."' where TagId in (".implode(',',$tagIds).")";
          	$this->query ($sql);
          }
        }
    }
    
    public function getClickCommentNumByVideoIds($videoIds){
    	if(!$videoIds){
    		return false;
    	}
    	$videoIds = (array)$videoIds;
    	$videoIdStr = implode(',', $videoIds);
    	$str = preg_replace('/(\d+)/', '%s', $videoIdStr);
    	$sql = "select VideoId,PlayNumShow,CommentNum,CommentPariseNum,QuestionNum,QuestionPariseNum from VideoProperty where VideoId IN (".$str.")";
    	$result = $this->query($sql, $videoIds);
    	$data = array();
    	while ($result->fetch_assoc()){
    			$nums = array(
    					'clickNum'=>$result->getData('PlayNum'),
    					'editClickNum'=>$result->getData('PlayNumShow'),
    					'commentNum'=>$result->getData('CommentNum')+$result->getData('CommentPariseNum')+$result->getData('QuestionNum')+$result->getData('QuestionPariseNum')
    			);
    			$data[$result->getData('VideoId')] = $nums;
    	}
    	return $data;
    }
    
    public function updateEditClickNumById($videoId, $num) {
    	$sql = 'update VideoProperty set PlayNumShow=%s where VideoId=%s LIMIT 1';
    	$arrValues = array (
    			$num,
    			$videoId
    	);
    	$this->query ( $sql, $arrValues );
    }
    
    public function getVideoPublishTimeByids($videoIds){
        $sql = 'select Id,PublishDate from Video where Id in ('.implode(',',$videoIds).')';
        $result = $this->query($sql,$videoIds);
        $infoList = array();
        while($row = $result->fetch_assoc()){
            $infoList[$row['Id']] = $row['PublishDate'];
        }
        return $infoList;
    }
    
    /**
     * 设置分享数
     * @param unknown_type $articleId
     */
    public function updateVideoShareNum($videoId){
    	$sql = "update VideoProperty set ShareNum=ShareNum+1 where VideoId=%s LIMIT 1";
    	$result  = $this->query($sql,array($videoId));
    }
    
    public function updateVideoCommentNum($videoId,$num){
    	$sql = "update VideoProperty set CommentNum=CommentNum+".$num." where VideoId=%s LIMIT 1";
    	$result  = $this->query($sql,array($videoId));
    }
    
    public function subtractCommentNum($id){
    	$sql = 'update VideoProperty set CommentNum=CommentNum-1 where VideoId=%s LIMIT 1';
    	$this->query($sql,array($id));
    }
    
    public function getVideoFile($videoId){
        $sql = "SELECT * FROM VideoFile WHERE VideoId=%s";
        $result = $this->query($sql,array($videoId));
        $videoArr = array();
        while ($row = $result->fetch_assoc()){
            $videoArr = $row;
        }
        return $videoArr;
    }
    
    public function deleteVideoFileById($videoId){
        $sql='DELETE FROM VideoFile WHERE VideoId = %s';
        $this->query($sql,array($videoId));
    }
    
    
    public function addVideoFile($videoId){
        $addSql="INSERT INTO VideoFile (VideoId,FilePath,Status,CreateTime) VALUES(%s,%s,0,%s)";
        $this->query($addSql,array($videoId,null,new \DateTime ()));
    }
    
    public function updateVideoFile($videoId){
        $updateSql = "UPDATE VideoFile  SET Status=0 WHERE VideoId = %s LIMIT 1";
        $this->query($updateSql,array($videoId));
    }
    
    public function addVideoFileLog($videoId,$userId){
        $sql="INSERT INTO VideoFileLog (VideoId,UserId,CreateTime) VALUES(%s,%s,%s)";
        $this->query($sql,array($videoId,$userId,new \DateTime ()));
    }
}
